// 导入vue-router模块
import Router from 'vue-router'
import Vue from 'vue'
// 导入路由组件
import Home from '../pages/Home/Home'
import Search from '../pages/Search/Search'
import Login from '../pages/Login/Login'
import Register from '../pages/Register/Register'
import Detail from '../pages/Detail/Detail'
import ShoppingCar from '../pages/ShoppingCar/ShoppingCar'
import Pay from '../pages/Pay/Pay'
import EndShopping from '../pages/endShopping/EndShopping'
import Good from '../pages//Good/Good'
// 使用插件
Vue.use(Router)
// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new Router({
  // 路由规则
  routes: [
    { path: '/', redirect: '/home' },
    { name: 'register', path: '/register', component: Register, meta: { title: '注册' } },
    { name: 'home', path: '/home', component: Home, meta: { title: '西航商城' } },
    { name: 'search', path: '/search', component: Search, meta: { title: '搜索' } },
    { name: 'login', path: '/login', component: Login, meta: { title: '登录' } },
    { name: 'detail', path: '/detail/:id', component: Detail, meta: { title: '详情' } },
    { name: 'shoppingCar', path: '/shoppingCar', component: ShoppingCar, meta: { title: '我的购物车' } },
    { name: 'pay', path: '/pay', component: Pay, meta: { title: '结算' } },
    { name: 'endshopping', path: '/endshopping', component: EndShopping, meta: { title: '支付' } },
    { name: 'good', path: '/good', component: Good, meta: { title: '支付成功' } }
  ]
})
router.beforeEach((to, from, next) => {
  if (to.path === '/shoppingCar') {
    if (localStorage.getItem('token')) {
      next()
    } else {
      next({ name: 'login' })
    }
  } else {
    next()
  }
})
router.afterEach((to, from) => {
  document.title = to.meta.title
  if (to.path === '/home') {
    document.body.style.background = '#f4f4f4'
  } else if (to.path === '/search' || to.path === '/detail' || to.path === '/shoppingCar') {
    document.body.style.background = '#fff'
  }
})
export default router
